import {useEffect, useRef, useState} from "react";
import {useLocation, useNavigate} from "react-router-dom";
import {Question} from "../types";
import BaseQuesItem from "../component/BaseQuesItem";

function PrintPage() {
    const location = useLocation();
    const navigate = useNavigate();
    const from: string = location.state?.from || '/';
    const ids: number[] = location.state?.ids || [];

    const [quesList, setQuesList] = useState<Question[]>([]);
    const [isLoading, setIsLoading] = useState(false);

    const doPrint = (quesList: Question[]) => {
        requestAnimationFrame(() => {
            window.ipcRender.invoke('ques:generatePdf', {
                ids: ids,
                answers: quesList.map((q) => q.answer)
            }).then((res) => {
                setIsLoading(false);
                if (res.status === 'success') {
                    console.log('导出成功！');
                } else if (res.status === 'cancelled') {
                    console.log('取消保存');
                } else {
                    console.log('导出失败：' + res.message);
                }
                navigate(from, {
                    state: {
                        status: res.status,
                        message: res.message
                    }
                }); // 返回来源页面
            });
        });
    };

    useEffect(() => {
        console.log("跳转来自:", from, ", 预备打印:", ids);
        setIsLoading(true);
        window.ipcRender.invoke('ques:getSelected', {
            ids: ids,
        }).then((res) => {
            setQuesList(res);
            doPrint(res);
        })

    }, []);

    return (
        <div>
            {/* 待打印考题 */}
            {quesList.map((question, index) => (
                <div key={question.id} className="flex items-start gap-2">
                    <div className="flex-1">
                        <BaseQuesItem printId={index + 1} question={question}/>
                    </div>
                </div>
            ))}
            {/* 白色蒙版 */}
            {isLoading && (
                <div className="print:hidden fixed inset-0 bg-white flex items-center justify-center z-50">
                    <span className="text-gray-700 text-2xl font-semibold animate-pulse">正在导出 PDF，请稍候…</span>
                </div>
            )}
        </div>
    )
}

export default PrintPage;